<template>
  <div class='container'>
    <el-dialog :title="`${data.id? '修改' :'新增'}学科`" :visible.sync="dialogshow" width="30%">
        <el-form  size="small" label-width="80px" :model="formModel" :rules="formRules" ref="form">
          <el-form-item label="学科内容" prop="subjectName">
            <el-input v-model="formModel.subjectName" ></el-input>
          </el-form-item>
         <el-form-item label="是否显示" prop="isFrontDisplay">
            <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="formModel.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
             ></el-switch>
         </el-form-item>
        </el-form>
     <div slot="footer" class="dialog-footer">
       <el-button @click="dialogshow = false">取 消</el-button>
       <el-button type="primary" @click="clickSubmit()">确 定</el-button>
     </div>
    </el-dialog></div>
</template>

<script>
// import { add } from '@/api/hmmm/subjects'
import { add, update } from '@/api/hmmm/subjects'
export default {
  name: 'SubjectsAdd',
  props: {
    data: {
      default: () => {},
      type: Object
    }
  },
  data () {
    return {
      dialogshow: false,
      formModel: {
        id: null,
        subjectName: null,
        isFrontDisplay: 1

      },
      currSubject: '',
      formRules: {
        subjectName: [{ required: true, message: '请输入学科名称', trigger: 'blur' }],
        isFrontDisplay: [{ required: true, type: 'number', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 打开对话框
    open () {
      this.dialogshow = true
      // 判断是否有ID，有ID就是修改，没有ID就是新增
      if (this.data.id) {
        const { id, subjectName, isFrontDisplay } = this.data
        this.formModel = { id, subjectName, isFrontDisplay }
      } else {
        this.formModel = {
          id: null,
          subjectName: null,
          isFrontDisplay: 1
        }
      }

      // 清除校验的效果
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 确定按钮提交功能
    clickSubmit (data) {
      // 发请求渲染页面
      // 先整个的表单进行校验
      this.$refs.form.validate(async flag => {
        if (!flag) return
        if (!this.data.id) {
          await add(this.formModel)
        // 提示用户添加成功
        } else {
          // 就是修改的功能
          await update(this.formModel)
        }

        this.$message.success('操作成功')
        // 渲染页面
        this.$emit('updateList')
      })
      // 渲染表格
      // 关闭对话框
      this.dialogshow = false
      // 重置表单
      this.formModel = {
        id: null,
        subjectName: null,
        isFrontDisplay: 1
      }
    }
  }
}
</script>

<style scoped lang='less'></style>
